import service.IUserService;
import service.ServiceInvocation;
import service.User;
import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;

/**
 * 1. 代理类 实现 InvocationHandler 接口 invoke方法
 * 2. Proxy 创建代理对象， ClassLoader， Interfaces, InvocationHandler
 *
 * 为什么目标类要实现接口？
 *  因为动态代理类继承了Proxy类
 * @author zhu_shuai
 * @since 8/4
 */
public class Demo01Proxy {
    public static void main(String[] args) throws IOException {
        IUserService user = new User();
        // 1. 创建代理类，实现 InvocationHandler 接口 invoke方法
        ServiceInvocation serviceInvocation = new ServiceInvocation(user);
        // 2. 创建代理对象
        IUserService proxyUser = (IUserService)Proxy.newProxyInstance(user.getClass().getClassLoader(), user.getClass().getInterfaces(), serviceInvocation);
        System.out.println("----------------------代理前-------------");
        user.setUserName("张三");
        System.out.println(user.getUserName());
        System.out.println("---------------------代理后----------------");
        proxyUser.setUserName("李四");
        System.out.println(proxyUser.getUserName());
        // 将代理类字节码保存到本地，反编译后查看继承了Proxy类
        byte[] proxyClass = ProxyGenerator.generateProxyClass(proxyUser.getClass()
                .getSimpleName(), proxyUser.getClass().getInterfaces());
        FileOutputStream fileOutputStream = new FileOutputStream(new File("e://proxy0.class"));
        fileOutputStream.write(proxyClass);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
